﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace VeryGoodSync.Provider
{
    class FolderSyncProvider : ISyncProvider
    {
        private string _target;
        private Regex[] _ignore;

        public void Init(Dictionary<string, string> arguments)
        {
            _target = arguments["Target"];
            _ignore = (arguments
                    .ContainsKey("Ignore")
                    ? arguments["Ignore"]
                    : "").Split('\n')
                .Select(a => a.Trim())
                .Where(a => !string.IsNullOrWhiteSpace(a))
                .Select(a => new Regex(a))
                .ToArray();
            if (!Directory.Exists(_target))
            {
                Directory.CreateDirectory(_target);
            }
        }

        public void Sync(string sourceDir)
        {
            var allFile = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories);
            foreach (var file in allFile)
            {
                var match = _ignore.Any(a => a.IsMatch(file));
                if (match) continue;
                var target = file.Replace(sourceDir, _target);
                var targetDir = Path.GetDirectoryName(target) ?? throw new Exception("无法获取目录名称");
                if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir);
                if (!File.Exists(target))
                {
                    File.Copy(file, target);
                    continue;
                }

                if (Ui.GetFileMd5(target) == Ui.GetFileMd5(file)) continue;
                File.Delete(target);
                File.Copy(file, target);
            }
        }

        public void Kill()
        {

        }

        public string Help()
        {
            return @"Target：目标文件夹
Ignore：忽略文件或路径，支持正则表达式，支持多行";
        }
    }
}
